package com.ate.gen;

import android.content.Context;

import org.greenrobot.greendao.query.QueryBuilder;

/**
 * @author Ate
 * @description:
 * @date :2020/12/25 13:34
 */
public class DaoManager {

    private static final String TAG = DaoManager.class.getSimpleName();

    // 数据库名称
    private static final String DB_NAME = "reliable.sqlite";

    // 多线程访问
    private volatile static DaoManager manager;

    private static DaoMaster.DevOpenHelper helper;

    private static DaoMaster daoMaster;

    private static DaoSession daoSession;

    private Context context;

    /**
     * 使用单例模式获得操作数据库的对象
     */
    public static DaoManager getInstance(){
        DaoManager instance = null;
        if (manager == null){
            synchronized (DaoManager.class){
                if (instance == null){
                    instance = new DaoManager();
                    manager = instance;
                }
            }
        }
        return manager;
    }

    public void init(Context context){
        this.context = context;
    }

    /**
     * 判断是否存在数据库
     * 如果没有则创建数据库
     */
    private DaoMaster getDaoMaster(){
        if (daoMaster == null){
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
//            MyOpenHelper myOpenHelper = new MyOpenHelper(context, DB_NAME, null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    /**
     * 完成对数据库的添加删除修改查询等的操作
     * 注：仅仅是一个接口
     */
    public DaoSession getDaoSession(){
        if (daoSession == null){
            if (daoMaster == null){
                daoMaster = getDaoMaster();
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    /**
     * 打开输出日志的操作
     * 注：默认是关闭的
     */
    public void setDebug(){
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
    }

    /**
     * 关闭所有的操作
     * 注：数据库开启之后，使用完毕必须要关闭
     */
    public void closeConnection(){
        closeHelper();
        closeDaoSession();
    }
    public void closeHelper(){
        if (helper != null){
            helper.close();
            helper = null;
        }
    }
    public void closeDaoSession(){
        if (daoSession != null){
            daoSession.clear();
            daoSession = null;
        }

    }

}